package com.loong.user.handler;

import com.loong.common.utils.TransformUtils;
import com.loong.user.business.ManageUserRoleAuthBusiness;
import com.loong.user.common.backend.param.ManageUserRoleAuthParam;
import com.loong.user.model.UserManageRoleAuth;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 角色分配资源服务
 * @Author: hzp
 * @Date: 2020-10-19 9:35
 */
@Component
public class ManageUserRoleAuthHandler {
    @Resource
    private ManageUserRoleAuthBusiness manageUserRoleAuthBusiness;

    /**
     * 保存角色资源
     * @param param
     */
    @Transactional
    public void save(ManageUserRoleAuthParam param) {
        Condition condition = new Condition(UserManageRoleAuth.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("roleId", param.getRoleId());
        //清除角色资源
        manageUserRoleAuthBusiness.deleteByCondition(condition);
        //保存角色资源
        manageUserRoleAuthBusiness.save(builderModels(param));
    }

    /**
     * 构建saveAndUpdate entity
     * @param param
     * @return
     */
    private List<UserManageRoleAuth> builderModels(ManageUserRoleAuthParam param){
        Long roleId = param.getRoleId();
        List<Long> resourceIds = param.getResourceIds();
        List<UserManageRoleAuth> modelList = new ArrayList<>();
        resourceIds.forEach(item->modelList.add(UserManageRoleAuth.builder().roleId(roleId).resourceId(item).build()));
        return  modelList;
    }


}
